package com.xishu.socket;

import com.xishu.util.MongoId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint("/websocket/{shopId}/{orderId}")
@Component
public class WebSocket {
    private static Logger logger = LoggerFactory.getLogger(WebSocket.class);
    private String socketId = MongoId.generateId();
    private Session session = null;

    public String getSocketId() {
        return socketId;
    }

    public void setSocketId(String socketId) {
        this.socketId = socketId;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    public String getSocketKey(Long shopId, Long orderId) {
        return shopId + ":" + orderId;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("shopId") Long shopId, @PathParam("orderId") Long orderId) throws IOException {
        this.session = session;
        WebSocketService.getInstance().addSocket(getSocketKey(shopId, orderId), this);
        this.sendMessage("success");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        logger.info("will close web socket is {}", this);
        WebSocketService.getInstance().removeSocket(this);
        logger.info("will close socket {}", socketId);
    }

    @OnError
    public void onError(Session session, Throwable thr) {
        logger.info("error:will close web socket is {}", this);
        WebSocketService.getInstance().removeSocket(this);
        logger.info("error:will close socket {}", socketId);
    }

    /**
     * 发送消息
     */
    public void sendMessage(String msg)  {
        try {
            if (session != null) {
                session.getBasicRemote().sendText(msg);
            } else {
                logger.info("send msg error, session is null");
            }
        } catch (Exception e) {
            logger.error("e", e);
        }

    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("WebSocket{");
        sb.append("socketId='").append(socketId).append('\'');
        sb.append(", session=").append(session);
        sb.append('}');
        return sb.toString();
    }
}
